package com.news.news.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.news.news.dao.NewsDao;
import com.news.news.dao.NewsTypeDao;
import com.news.news.modle.News;
import com.news.news.modle.NewsType;
import com.news.news.util.JWTUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * Created by 罗铠威 on 2023/8/29 16:21
 * type:
 */
@Service
@Transactional
public class NewsService {

    @Resource
    NewsDao newsDao;


    public PageInfo<News> NewsList(@RequestBody News news) {
        PageHelper.startPage(news.getPageNum(),news.getPageSize());
        ArrayList<News> newses = newsDao.newsList(news);
//        System.out.println(roles);
        PageInfo<News> pageInfo = new PageInfo<>(newses);
        return pageInfo;
    }

    public void saveNews(News news, String token) {
        news.setAdminid(JWTUtil.getTokenInfo(token).getClaim("id").asInt());
        //保存信息并返回ID
        newsDao.saveNews(news);
        //添加新闻与新闻类型关系
        if(news.getNewsTypeid()!=null){
            for (Integer NewsTypeid : news.getNewsTypeid()) {
                newsDao.addNewstypeRole(news.getId(),NewsTypeid);
            }
        }



    }

    public void UpdateNewsState(News news) {
        newsDao.UpdateNewsState(news);
    }

    public News findNewsById(Integer id) {
        News newsById = newsDao.findNewsById(id);
        if(newsById.getNewsTypeList()!=null){
            //将新闻类型的列表取出id,转化为数组
            Integer[] newsTypeid = new Integer[newsById.getNewsTypeList().size()];
            for (int i = 0; i <newsTypeid.length ; i++) {
                newsTypeid[i]=newsById.getNewsTypeList().get(i).getId();
            }
            //存入数组
            newsById.setNewsTypeid(newsTypeid);
        }
        return newsById;
    }

    public void updateNews(News news, String token) {
        news.setAdminid(JWTUtil.getTokenInfo(token).getClaim("id").asInt());
        //修改新闻信息
        newsDao.updateNews(news);
        //删除新闻与新闻类型关系
        newsDao.deleteNewstypeRole(news.getId());
        //添加新闻与新闻类型关系
        if(news.getNewsTypeid()!=null){
            for (Integer NewsTypeid : news.getNewsTypeid()) {
                newsDao.addNewstypeRole(news.getId(),NewsTypeid);
            }
        }
    }

    public void deleteNewsById(Integer id) {
        newsDao.deleteNewsById(id);
    }

    public ArrayList<NewsType> findNewsTypeList() {
       return newsDao.findNewsTypeList();
    }
}
